
package alipay;

import android.app.Activity;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;

import com.alipay.sdk.app.PayTask;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONException;
import org.json.JSONObject;

import share.Const;
import share.HttpIP;

/**
 * 调用支付宝支付startPay（）方法
 */

public class PayToolPayMoney {

    private static PayToolPayMoney instance;

    private PayCallback callback;

    public static PayToolPayMoney getInstance() {
        if (instance == null) {
            instance = new PayToolPayMoney();
        }
        return instance;
    }

    public void startPay(Activity context, PayCallback callback, String[] params) {
        this.callback = callback;

        new PayAysncTask(context).execute(params);
    }

    private class PayAysncTask extends AsyncTask<String, Void, String> {

        private Activity context;

        PayAysncTask(Activity context) {
            this.context = context;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
//            if (progress == null) {
//                progress = new SVProgressHUD(context);
//            }
//            progress.showWithStatus("加载中...");
        }

        @Override
        protected String doInBackground(String... params) {
            Request<String> mRequest = NoHttp.createStringRequest(HttpIP.Pay, Const.POST);
            mRequest.addHeader("token",params[0]);
            mRequest.add("payType", params[1]);
            mRequest.add("orderId", params[2]);
            Response<String> response = NoHttp.startRequestSync(mRequest);
            if (response.isSucceed()) {
                Log.i("onSucceed", "请求成功：\n" + response.get());
/**
 * { "apiPay":
 *    { "msg":null,
 *      "msgcode":100,
 *      "success":true,
 *      "object":"partner=\"2088421601928890\"&seller_id=\"2088421601928890\"&out_trade_no=\"b8784aa7d0c34d4ba4140ad21f219907\"&subject=\"乐谱，期刊支付费用\"&body=\"乐谱，期刊支付费用\"&total_fee=\"0.01\"&notify_url=\"http://122.114.98.247:8668/Zlyy/app/alipays/aliPayMeth\"&service=\"mobile.securitypay.pay\"&payment_type=\"1\"&_input_charset=\"utf-8\"&it_b_pay=\"30m\"&return_url=\"m.alipay.com\"&sign=\"WtnejbZhKXjsW8fTAcuD9pwNAzfY0359iz%2BuOcHsQ5l6YGQWTKIn33jI%2B2LQpWUULAZHfCjmubeADJEEMJSKSb%2FiXU4vP2GYxXBaX9ujRO7oKbCT86ZQn9sVzI7OXPeTBrGsz9cgKuoGYozh9pR35vTptYETSjI640nSBJENeqo%3D\"&sign_type=\"RSA\""
 *    }
 * }
 */

                try {
                    JSONObject obj = new JSONObject(response.get());
                    if (obj == null) {
                        return "支付失败！";
                    }
//                    String payInfo = obj.getString("object");
                    JSONObject object = obj.getJSONObject("object");
                    String payInfo = object.getString("info");
                    // 构造PayTask 对象
                    PayTask alipay = new PayTask(context);

                    // 调用支付接口，获取支付结果
                    return alipay.pay(payInfo, true);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            return "支付失败！"; // 请求失败
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
//            if (progress != null) {
//                progress.dismiss();
//            }

            if (!TextUtils.equals("支付失败！", result)) {
                PayResult payResult = new PayResult(result);
/**
 * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
 * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
 * docType=1) 建议商户依赖异步通知
 */

                String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                Log.i("PayResult", "onPostExecute: " + resultInfo);

                String resultStatus = payResult.getResultStatus();
                // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                // 判断resultStatus 为非"9000"则代表可能支付失败
                // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误

                if (TextUtils.equals("9000", resultStatus)) callback.doWork(resultStatus, true);
                else callback.doWork(resultStatus, false);
            } else {
                callback.doWork(result, false);
            }
        }

    }

    public interface PayCallback {
        public void doWork(String payResult, boolean isDone);
    }

}

